<template>
  <section class="todoapp">
    <todo-header @add="handleadd"></todo-header>
    <todo-main :list="list2" @del="handleDel" @state="handlestate" @changAll="handleAll"></todo-main>
    <todo-footer :list="list" @delCompleted="handleclear" :flag="flag" @changeFlag="val=>{flag = val}"></todo-footer>
  </section>
</template>

<script>
import TodoFooter from "./components/TodoFooter.vue";
import TodoHeader from "./components/TodoHeader.vue";
import TodoMain from "./components/TodoMain.vue";
export default {
  data() {
    return {
      list:JSON.parse(localStorage.getItem('todolist')) || [],
      // list: [
      //   { id: 12, name: "吃饭", isDone: false },
      //   { id: 14, name: "听歌", isDone: true },
      //   { id: 23, name: "洗澡", isDone: true },
      //   { id: 34, name: "睡觉", isDone: false },
      //   { id: 35, name: "游戏", isDone: false },
      // ],
      flag:1,   // 1 显示全部任务； 2 显示进行中； 3 显示已完成
    };
  },
  components: { TodoHeader, TodoMain, TodoFooter },
  methods: {
    //删除数据
    handleDel(id) {
      // filter 筛选满足条件的
      return (this.list = this.list.filter((item) => item.id !== id));
    },
    //添加数据
    handleadd(todoname) {
      //unshift 像数组开头添加数据
      return this.list.unshift({
        id: +new Date(),
        name: todoname,
        isDone: false,
      });
    },
    //改变复选框的状态
    handlestate(id) {
      const row = this.list.find((item) => item.id === id);
      row.isDone = !row.isDone;
    },
    //清除已完成的数据
    handleclear(){
      return this.list = this.list.filter(item=>item.isDone === false)
    },
    //改变小复选框的状态
    handleAll(val){
      return this.list.forEach(item=>item.isDone = val)
    }
  },
  //计算属性
  computed: {
    list2(){
      if(this.flag === 1){
        return this.list
      } else if(this.flag === 2){
        return this.list.filter(item=>item.isDone === false)
      } else{
        return this.list.filter(item=>item.isDone === true)
      }
    }
  },
  //侦听器
  watch: {
    list:{
      handler(val){
        localStorage.setItem('todolist',JSON.stringify(val))
      },
      deep:true
    }
  }
};
</script>

<style></style>
